<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j discount-detail page-discount-detail">
    <div class="banner">
      <img
        v-if="!discountDetail.isPcBackgroundPicError"
        :src="checkFileUrl(discountDetail.pcBackgroundPic)"
        class="bg"
        alt
        @error="handleBackgroundPicError"
      >
      <img
        v-else
        src="@/assets/img/def.png"
        class="bgError"
        alt
      >
      <div class="text-box">
        <div class="time">
          <span class="time-icon" />
          {{ $t('discountDetail.DistanceToEnd') }}
          <div
            v-if="day"
            class="much-time"
          >
            <span class="day">{{ day }}</span>{{ $t('day') }}
          </div>
          <div class="number-box">
            <span class="number">{{ hour }}</span>
            <span class="colon">:</span>
            <span class="number">{{ min }}</span>
            <span class="colon">:</span>
            <span class="number">{{ second }}</span>
          </div>
        </div>
        <div class="shop-logo">
          <img
            :src="checkFileUrl(discountDetail.shopLogo)"
            alt
            @error="handlePicError"
          >
        </div>
        <div class="shop-name">
          {{ discountDetail.shopName }}{{ $t('discountDetail.SpecialSession') }}
        </div>
        <div class="info">
          {{ discountDetail.discountName }}
        </div>
      </div>
    </div>
    <div
      v-if="discountProdList.length"
      class="goods-list discount-prod"
    >
      <div class="list-con">
        <!-- 商品 -->
        <div
          v-for="item in discountProdList"
          :key="item.prodId"
          class="item"
          @click="toDiscountProdDet(item.prodId)"
        >
          <div class="goods-img">
            <img
              v-if="item.pic"
              :src="checkFileUrl(item.pic)"
              alt
              @error="handlePicError"
            >
            <img
              v-else
              src="@/assets/img/def.png"
              alt
            >
          </div>
          <div class="goods-msg">
            <div class="goods-name">
              {{ item.prodName }}
            </div>
            <div class="activity-price">
              {{ $t('discountDetail.eventReferencePrice') }}：
              <div class="price">
                ￥
                <span class="big">{{ parsePrice(item.activityPrice)[0] }}</span>
                .{{ parsePrice(item.activityPrice)[1] }}
              </div>
              <div class="old-price">
                ￥{{ item.price.toFixed(2) }}
              </div>
            </div>
          </div>
        </div>
        <!-- /商品 -->
      </div>
      <!-- 页码 -->
      <pagination
        v-model="current"
        :pages="pages"
        @change-page="getDiscountProdList"
      />
      <!-- /页码 -->
    </div>
    <!-- 商品列表为空 -->
    <empty-all-tips
      v-if="isEmpty"
      :text="$t('sorryNoRelatedProducts')"
      :back="$t('lookAtOther')"
      :back-path="'/special-discount'"
    />
    <!-- 商品列表为空 -->
  </div>
</template>

<script setup>
import defPng from '@/assets/img/def.png'
import { checkFileUrl } from '@/utils/index.js'

const route = useRoute()
const router = useRouter()

const discountDetail = ref({}) // 活动详情
const endTime = ref('') // 结束时间
const discountId = ref(route.query.discountId) // 接收活动列表id
onMounted(() => {
  // 设置网页标题
  document.title = $t('commonHead.limitedTimeOffer')
  // 获取活动详情
  http.get('/marking/discount/getDiscountByDiscountId/' + discountId.value).then(({ data }) => {
    discountDetail.value = data
    endTime.value = data.endTime
    countTime()
  }).catch(() => {
    router.push('/special-discount')
  })

  // 获取限时特惠商品列表
  getDiscountProdList(1)
})

// 离开时结束倒计时
onBeforeUnmount(() => {
  clearTimeout(timer)
})

/**
 * 加载默认图片
 */
const handlePicError = (e) => {
  e.target.src = defPng
}

const handleBackgroundPicError = () => {
  discountDetail.isPcBackgroundPicError = true
}

const day = ref(0) // 天
const hour = ref(0) // 时
const min = ref(0) // 分
const second = ref(0) // 秒
const discountProdList = ref([]) // 限时特惠商品列表
const current = ref(1) // 当前页数
const pages = ref(1) // 总页数
let timer = null
const isEmpty = ref(false)
// 倒计时
const countTime = () => {
  // 获取当前时间
  const date = new Date()
  const now = date.getTime()

  // // 设置截止时间
  const end = new Date(endTime.value.toString().replace(/-/g, '/')).getTime()

  // 时间差
  const leftTime = end - now

  // 定义变量 d,h,m,s保存倒计时的时间
  if (leftTime >= 0) {
    // 天
    day.value = Math.floor(leftTime / 1000 / 60 / 60 / 24)
    // 时
    const h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
    hour.value = h < 10 ? '0' + h : h
    // 分
    const m = Math.floor(leftTime / 1000 / 60 % 60)
    min.value = m < 10 ? '0' + m : m
    // 秒
    const s = Math.floor(leftTime / 1000 % 60)
    second.value = s < 10 ? '0' + s : s
  } else {
    day.value = 0
    hour.value = '00'
    min.value = '00'
    second.value = '00'
  }
  // 等于0的时候不调用
  if (Number(day.value) === 0 && Number(hour.value) === 0 && Number(min.value) === 0 && Number(second.value) === 0) {
    router.push({ path: '/special-discount' })
  } else {
    // 递归每秒调用countTime方法，显示动态时间效果,
    timer = setTimeout(countTime, 1000)
  }
}

// 获取限时特惠商品列表
const getDiscountProdList = (cur) => {
  isEmpty.value = false
  http.get('/marking/discount/prodList', {
    params: {
      discountId: discountId.value, // 活动id
      current: cur, // 当前页
      size: 20
    }
  }).then(({ data }) => {
    discountProdList.value = data.records
    isEmpty.value = !discountProdList.value.length
    pages.value = data.pages
  })
}

// 价格过滤
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

// 跳转到商品详情
const toDiscountProdDet = (prodId) => {
  const newPage = router.resolve({ path: '/detail/', query: { prodId } })
  window.open(newPage.href, '_blank', 'noopener,noreferrer')
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
